package com.xuan.juc.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/*
* 线程之间的通讯问题：生产者和消费者问题！
* 线程交替执行 A B C 操作同一个变量 num=0
* A B C 顺序执行
*
*
* */
public class providerCustomer3 {
    public static void main(String[] args) {
        Data3 data3 = new Data3();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data3.printA();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data3.printB();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data3.printC();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "C").start();
    }
}

// 资源类
// 等待 业务 通知
class Data3{

    private int num = 1;
    private Lock lock = new ReentrantLock();
    Condition conditionA = lock.newCondition();
    Condition conditionB = lock.newCondition();
    Condition conditionC = lock.newCondition();

    public void printA() throws InterruptedException {
        lock.lock();
        try {
            while (num != 1) {
                // 等待
                conditionA.await();
            }
            System.out.println(Thread.currentThread().getName() + "=>AAA");
            num = 2;
            // 通知B
            conditionB.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printB() throws InterruptedException {
        lock.lock();
        try {
            while (num != 2) {
                // 等待
                conditionB.await();
            }
            System.out.println(Thread.currentThread().getName() + "=>BBB");
            num = 3;
            // 通知C
            conditionC.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }


    public void printC() throws InterruptedException {
        lock.lock();
        try {
            while (num != 3) {
                // 等待
                conditionC.await();
            }
            System.out.println(Thread.currentThread().getName() + "=>CCC");
            num = 1;
            // 通知A
            conditionA.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}

